package com.resou.reader.bookdetail.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.resou.reader.R;

/**
 * Created by ${Garrett} on 2018/9/5.
 * Contact me krouky@outlook.com
 */
public class CommentInputDialog extends Dialog implements View.OnClickListener {

    private ImageView mCancelImage;
    private TextView mInputText;
    private FrameLayout mInputParent;
    private TextView mPublishBtn;

    private OnPublishCallback callback;

    public CommentInputDialog(@NonNull Context context, OnPublishCallback callback) {
        super(context);
        this.callback = callback;
        setContentView(R.layout.input_comment_layout);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCancelImage = findViewById(R.id.cancel_item);
        mInputText = findViewById(R.id.comment_input_text);
        mInputParent = findViewById(R.id.autoCompleteTextView);
        mPublishBtn = findViewById(R.id.button);

        mCancelImage.setOnClickListener(this);
        mInputParent.setOnClickListener(this);
        mPublishBtn.setOnClickListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
        mPublishBtn.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(mInputText, InputMethodManager.SHOW_FORCED);
            }
        }, 50);

    }

    @Override
    public void onClick(View v) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        switch (v.getId()) {
            case R.id.cancel_item:
                imm.hideSoftInputFromWindow(mInputText.getWindowToken(), 0);
                dismiss();
                break;
            case R.id.autoCompleteTextView:
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.button:
                if (TextUtils.isEmpty(mInputText.getText())) {
                    Toast.makeText(getContext(), "请输入内容", Toast.LENGTH_SHORT).show();
                } else {
                    imm.hideSoftInputFromWindow(mInputText.getWindowToken(), 0);
                    dismiss();
                    callback.onPublish(mInputText.getText().toString());
                    mInputText.setText("");
                }
                break;

        }
    }

    public interface OnPublishCallback {
        void onPublish(String str);
    }
}
